package db

import (
	"github.com/pkg/errors"
	logger "github.com/sirupsen/logrus"
	"gopkg.in/yaml.v3"
	"os"
	"path"
	"time"
)

var HomeDir = ""

func init() {
	if HomeDir == "" {
		HomeDir, _ = os.Getwd()
	}
}

type Config struct {
	DbConnect  *DbConfig `yaml:"database"`
	Services   []string  `yaml:"services"`
	Env        string    `yaml:"env"`
	DbSupports []string  `yaml:"db_supports"`
}
type DbConfig struct {
	Url      string `yaml:"url"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Db       string `yaml:"db"`
}

type MayaService struct {
	ID          int64  `json:"id" gorm:"primary_key"`
	ServiceName string `json:"serviceName" gorm:"service_name"`
	NamespaceID string `json:"namespaceId" gorm:"namespace_id"`
	NSRPCID     string `json:"namespaceId" gorm:"ns_rpc_id"`
	Cgroup      string `json:"cgroup" gorm:"cgroup"`
	RRevision   uint64
	LRevision   uint64
	CCRevision  uint64
	Token       string
	Comment     string
	Flag        int
	Ctime       time.Time
	Meta        string `gorm:"type:json;default:{}"`
	Mtime       time.Time
}

func (MayaService) TableName() string {
	return "t_maya_service"
}

type MayaServiceLocation struct {
	Service    *MayaService
	ConfigList []ConfigInfo
}

type ConfigInfo struct {
	ID               int64  `gorm:"primary_key"`
	DataID           string `gorm:"not null"`
	GroupID          string `gorm:"default:null"`
	Content          string `gorm:"not null"`
	MD5              string `gorm:"default:null"`
	GmtCreate        time.Time
	GmtModified      time.Time
	SrcUser          string `gorm:"type:text"`
	SrcIP            string `gorm:"default:null"`
	AppName          string `gorm:"default:null"`
	TenantID         string `gorm:"default:''"`
	CDesc            string `gorm:"default:null"`
	CUse             string `gorm:"default:null"`
	Effect           string `gorm:"default:null"`
	Type             string `gorm:"default:null"`
	CSchema          string `gorm:"type:text"`
	EncryptedDataKey string `gorm:"not null"`
	IsUpdate         bool
}

func (ConfigInfo) TableName() string {
	return "config_info"
}

/**
 * 中间表
 */
type ServiceConfig struct {
	ConfigId    int64  `json:"configId" gorm:"primary_key"`
	ServiceId   int64  `json:"service_Id" gorm:"service_id"`
	DataId      string `json:"dataId" gorm:"data_id"`
	NamespaceId string `json:"namespace_id" gorm:"namespace_id"`
	GroupId     string `json:"groupId" gorm:"group_id"`
}

func (ServiceConfig) TableName() string {
	return "t_service_config"
}

func Load(filePath string) (*Config, error) {
	if filePath == "" {
		err := errors.New("invalid config file path")
		return nil, err
	}
	filePath = path.Join(HomeDir, filePath)
	logger.Infof("load config from %v", filePath)
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = file.Close()
	}()

	conf := &Config{Env: "prod"}
	if err = yaml.NewDecoder(file).Decode(conf); err != nil {
		logger.Errorf("db config is error,exit %s", err)
		return nil, err
	} else if conf.DbConnect == nil || len(conf.DbConnect.Db) == 0 || len(conf.DbConnect.Url) == 0 || len(conf.DbConnect.Password) == 0 || len(conf.DbConnect.Password) == 0 {
		return nil, errors.New("数据库配置里面不能为空")
	} else if len(conf.Services) == 0 {
		return nil, errors.New("改变服务不能为空")
	} else if len(conf.DbSupports) == 0 {
		return nil, errors.New("数据库服务地址链接不能为空")
	}
	return conf, nil
}
